/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
//importing packages
package com.globussoft.filesystem;


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor. this is comment.
 */
import com.cloudminga.gui.*;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Enumeration;
import javax.swing.Icon;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.UIManager;
import javax.swing.plaf.ColorUIResource;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeCellRenderer;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import javax.swing.JFileChooser;
import javax.swing.table.DefaultTableModel;

/**
 * @version 1.1 01/15/99
 */
public class FileTree extends JPanel {

    DefaultTableModel dtm;

    public static CheckNode DrawFolder(File file, CheckNode check) {
        /* Beginning of if block
        checking whether the file is directory or not */
        try {
            if (file.isDirectory()) {
                String[] children = file.list();

                int len = children.length;
                ////("length"+len);
                CheckNode[] ch = new CheckNode[len];
                for (int i = 0; i < len; i++) {
                    try {
                        if (new File(file, children[i]).isDirectory() && children[i].toLowerCase().equals("windows") == false && new File(file, children[i]).isHidden() == false) {
                            ch[i] = new CheckNode(children[i]);
                            check.add(ch[i]);
                            //DrawFolder(new File(file, children[i]), ch[i]);
                        }
                    } catch (Exception ex) {

                        Logger.LogText("Exception : " + ex.getMessage());

                    }

                }
            }/*end of if block*/ else {
            }
        } catch (Exception ex) {
        }
        return check;
    }
    /*code for Directory Tree Structure*/

    public static JTree getTree(String path) {
        File[] file = File.listRoots();
        int len = file.length;
        CheckNode[] ch = new CheckNode[len + 1];
        ch[0] = new CheckNode("My Computer");

        for (int i = 0; i < len; i++) {
            try {
                ch[i] = DrawFolder(file[i], new CheckNode(file[i].toString()));
                ch[0].add(ch[i]);
            } catch (NullPointerException ex) {
                ex.printStackTrace();
            }
        }
        return new JTree(ch[0]);
    }
    public static String path = System.getProperty("user.home");

    public FileTree() {
        setLayout(new GridLayout());
        JTree tree = getTree(path);
        tree.setCellRenderer(new CheckRenderer());

        /*Sets the TreeCellRenderer
        that will be used to draw each cell.*/

        tree.getSelectionModel().setSelectionMode(
                TreeSelectionModel.SINGLE_TREE_SELECTION);
        tree.putClientProperty("JTree.lineStyle", "Angled");
        tree.addMouseListener(new NodeSelectionListener(tree));
        final JScrollPane jsp = new JScrollPane(tree);
        jsp.setSize(800, 1000);
        this.add(jsp, BorderLayout.CENTER);
        this.setSize(1000, 1000);

    }

    class CheckBoxRightTable extends JCheckBox {

        CheckBoxRightTable() {
            JCheckBox cb = new JCheckBox();



        }
    }

    /*code to display filelist of subsequest directories on mouseclickevent
    of the node of the tree*/
    class NodeSelectionListener extends MouseAdapter {

        JTree tree;      /*instance of JTree*/


        NodeSelectionListener(JTree tree) {

            this.tree = tree;
        }

        @Override
        public void mouseClicked(MouseEvent e) {
            int x = e.getX();
            int y = e.getY();
            int row = tree.getRowForLocation(x, y);
            /* for getting absolutefilepath */
            TreePath path = tree.getPathForRow(row);

            try {
                if (path != null) {
                    String path_str = path.toString();
                    path_str = path_str.replace("[", "");
                    path_str = path_str.replace("]", "");
                    String path_var[] = path_str.split(",");
                    String absult_path = "";
                    String absult_path1 = "";
                    for (int i = 1; i < path_var.length; i++) {
                        if (i == 1) {

                            absult_path = path_var[i].replace("\\", "/");
                            absult_path1 = absult_path;

                        } else {
                            absult_path = absult_path + "\\" + path_var[i].trim();
                            absult_path1 = absult_path1 + "\\" + path_var[i].trim();

                        }

                    }


                    dtm = (DefaultTableModel) MainForm.fileTable.getModel();
                    dtm.getDataVector().removeAllElements();

                    /*file list are generating here*/
                    try {

                        FileList filelist = new FileList();
                        /*filelist are store in a hashmap*/
                        HashMap hm = filelist.setRootDir(absult_path1);


                        int i = 0;
                        Date date;
                        String strDate;
                        SimpleDateFormat sdf;
                        JFileChooser filechooser = new JFileChooser(); //To get the FileType
                        String filetype;
                        String size = null;
                        long kb = 0, gb = 0, mb = 0;
                        long filesize;
                        while (!hm.isEmpty()) {
                            String filepath = (String) hm.get(i);

                            File file = new File(filepath);

                            filetype = filechooser.getTypeDescription(file);
                            date = new Date();
                            sdf = new SimpleDateFormat("dd/MM/yy hh:mm:ss");
                            strDate = sdf.format(date);
                            filesize = file.length();
                            hm.remove(i);

                            /*code to check the file size in Bytes,KB,MB,GB*/

                            if (filesize < 1024) {
                                size = String.valueOf(filesize) + "" + "bytes";
                            } else if (filesize >= 1024 || filesize < 1024 * 1024) {
                                kb = filesize / 1024;
                                size = String.valueOf(kb) + " " + "KB";

                            } else if (filesize >= 1024 * 1024 || filesize < 1024 * 1024 * 1024) {
                                mb = filesize / (1024 * 1024);
                                size = String.valueOf(mb) + " " + "MB";

                            } else if (filesize >= 1024 * 1024 * 1024) {
                                gb = filesize / (1024 * 1024 * 1024);
                                size = String.valueOf(gb) + " " + "GB";

                            }


                            /*an object Array to get the File */

                            Object[] obj = {null, file.getName(), hm.get(i), size, filetype, strDate};
                            dtm.addRow(obj);//adding the filedata in  a fileTable row



                            i++;
                        }
                    } catch (NullPointerException ex) {
                    }
                }
            } catch (NullPointerException ex) {
            }


            if (path != null) {
                CheckNode node = (CheckNode) path.getLastPathComponent();
                boolean isSelected = !(node.isSelected());
                node.setSelected(isSelected);
                if (node.getSelectionMode() == CheckNode.DIG_IN_SELECTION) {
                    if (node.isSelected) {
                        tree.expandPath(path);
                    } else {
                        tree.collapsePath(path);
                    }
                }

                ((DefaultTreeModel) tree.getModel()).nodeChanged(node);

                if (row == 0) {
                    //                  tree.revalidate();
                    tree.repaint();
                }
            }
        }
    }
}

/*class defines the requirements for an object that displays a tree node*/
class CheckRenderer extends JPanel implements TreeCellRenderer, ItemListener {

    protected JCheckBox checkboxlefttable;
    protected TreeLabel nodelabel;
//    CheckBoxRightTable chk;
//

    public CheckRenderer() {
        setLayout(null);
        checkboxlefttable = new JCheckBox();
        add(checkboxlefttable);
        //sendChecboxreference(checkboxlefttable);
        checkboxlefttable.addItemListener(this);
        add(nodelabel = new TreeLabel());
        checkboxlefttable.setBackground(Color.white);
        nodelabel.setForeground(UIManager.getColor("Tree.textForeground"));
    }

    /*code to Set the value of the current tree cell to value.*/
    public Component getTreeCellRendererComponent(JTree tree, Object value,
            boolean isSelected, boolean expanded, boolean leaf, int row,
            boolean hasFocus) {
        String stringValue = tree.convertValueToText(value, isSelected,
                expanded, leaf, row, hasFocus);
        setEnabled(tree.isEnabled());
        checkboxlefttable.setSelected(((CheckNode) value).isSelected());
        nodelabel.setFont(tree.getFont());/*sets font*/
        nodelabel.setText(stringValue);/*sets Text*/
        nodelabel.setSelected(isSelected);
        nodelabel.setFocus(hasFocus);

        if (leaf) {

            nodelabel.setIcon(UIManager.getIcon("Tree.openIcon"));
        } else if (expanded) {
            nodelabel.setIcon(UIManager.getIcon("Tree.openIcon"));
        } else {
            nodelabel.setIcon(UIManager.getIcon("Tree.openIcon"));
        }
        return this;
    }

    @Override
    /*sets the size of CheckBox*/
    public Dimension getPreferredSize() {
        Dimension checkboxsize = checkboxlefttable.getPreferredSize();
        Dimension nodelabelsize = nodelabel.getPreferredSize();
        return new Dimension(checkboxsize.width + nodelabelsize.width,
                (checkboxsize.height < nodelabelsize.height ? nodelabelsize.height
                : checkboxsize.height));
    }

    @Override
    //sets the layout of checkbox
    public void doLayout() {
        Dimension checkboxsize = checkboxlefttable.getPreferredSize();
        Dimension nodelabelsize = nodelabel.getPreferredSize();
        int checkboxheight = -1;
        int nodelabelheight = -1;
        if (checkboxsize.height < nodelabelsize.height) {
            checkboxheight = (nodelabelsize.height - checkboxsize.height) / 2;
        } else {
            nodelabelheight = (checkboxsize.height - nodelabelsize.height) / 2;
        }
        checkboxlefttable.setLocation(0, checkboxheight);
        checkboxlefttable.setBounds(0, checkboxheight, checkboxsize.width, checkboxsize.height);
        nodelabel.setLocation(checkboxsize.width, nodelabelheight);
        nodelabel.setBounds(checkboxsize.width, nodelabelheight, nodelabelsize.width, nodelabelsize.height);
    }

    @Override
    //set the backgroundcolor of the Checkbox
    public void setBackground(Color color) {
        if (color instanceof ColorUIResource) {
            color = null;
        }
        super.setBackground(color);
    }

    /*code for Checkbox State Change */
    public void itemStateChanged(ItemEvent itemEvent) {



        int k = 0;

        if (checkboxlefttable.isSelected()) {
            for (k = 0; k < MainForm.fileTable.getRowCount(); k++) {
                MainForm.fileTable.setValueAt(Boolean.TRUE, k, 0);
//                MainForm.fileTable.tableChanged(new TableModelEvent(MainForm.fileTable.getModel()));
//                this.revalidate();
//                this.repaint();

            }
        } else {
            MainForm.fileTable.setValueAt(Boolean.FALSE, k, 0);
        }
    }

    /* Code for fileTree NodeLabel */
    public class TreeLabel extends JLabel {

        boolean isSelected;
        boolean hasFocus;

        public TreeLabel() {
        }

        @Override
        public void paint(Graphics g) {
            String str;
            if ((str = getText()) != null) {
                if (0 < str.length()) {
                    if (isSelected) {
                        g.setColor(UIManager.getColor("Tree.selectionBackground"));
                    } else {
                        g.setColor(UIManager.getColor("Tree.textBackground"));
                    }
                    Dimension d = getPreferredSize();
                    int imageOffset = 0;
                    Icon currentI = getIcon();
                    if (currentI != null) {
                        imageOffset = currentI.getIconWidth() + Math.max(0, getIconTextGap() - 4);
                    }
                    g.fillRect(imageOffset, 0, d.width - 2 - imageOffset,
                            d.height);
                    if (hasFocus) {
                        g.setColor(UIManager.getColor("Tree.selectionBorderColor"));
                        g.drawRect(imageOffset, 0, d.width - 2 - imageOffset,
                                d.height - 1);
                    }
                }
            }
            super.paint(g);
        }

        @Override
        public Dimension getPreferredSize() {
            Dimension nodelabelDimension = super.getPreferredSize();
            if (nodelabelDimension != null) {
                nodelabelDimension = new Dimension(nodelabelDimension.width + 5,
                        nodelabelDimension.height);
            }
            return nodelabelDimension;
        }

        public void setSelected(boolean isSelected) {
            this.isSelected = isSelected;
        }

        public void setFocus(boolean hasFocus) {
            this.hasFocus = hasFocus;
        }
    }
}
/* class use for expanding the tree on selection of the checkbox*/
class CheckNode extends DefaultMutableTreeNode {

    /* use if the node should be expand if selected and if possible.*/
    public final static int SINGLE_SELECTION = 0;

    /* use if the node shouldnot expand if selected */
    public final static int DIG_IN_SELECTION = 4;
    protected int selectionMode;
    protected boolean isSelected;

    public CheckNode() {
        this(null);
    }

    public CheckNode(Object userObject) {
        this(userObject, true, false);
    }

    public CheckNode(Object userObject, boolean allowsChildren,
            boolean isSelected) {
        super(userObject, allowsChildren);
        this.isSelected = isSelected;
        setSelectionMode(DIG_IN_SELECTION);
    }

    public void setSelectionMode(int mode) {
        selectionMode = mode;
    }

    public int getSelectionMode() {
        return selectionMode;
    }

    public void setSelected(boolean isSelected) {
        this.isSelected = isSelected;

        if ((selectionMode == DIG_IN_SELECTION) && (children != null)) {
            Enumeration e = children.elements();
//            while (e.hasMoreElements()) {
//                CheckNode node = (CheckNode) e.nextElement();
//                node.setSelected(isSelected);
//            }
        }
    }

    public boolean isSelected() {
        return isSelected;
    }
}



